package cn.dsscm.controller;

import cn.dsscm.pojo.Product;
import cn.dsscm.pojo.ProductCategory;
import cn.dsscm.service.ProductCategoryService;
import cn.dsscm.service.ProductService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.List;

@Controller
@RequestMapping("/sys/product")
public class ProductController {

    private static final Logger logger = LoggerFactory.getLogger(ProductController.class);
    private static final String PRODUCT_LIST_REDIRECT = "redirect:/sys/product/list";

    @Resource
    private ProductService productService;
    @Resource
    private ProductCategoryService productCategoryService;

    @GetMapping(value = {"/list", "/list.html"})
    public String productList(
            @RequestParam(required = false) String productName,
            @RequestParam(required = false) Integer categoryLevel3Id,
            @RequestParam(defaultValue = "1") Integer pageIndex,
            Model model) {
        try {
            int pageSize = 10;
            pageSize = Math.max(1, Math.min(pageSize, 100));

            int totalCount = productService.getProductCount(productName, null, null, categoryLevel3Id);
            int totalPageCount = (int) Math.ceil((double) totalCount / pageSize);

            pageIndex = Math.max(1, Math.min(pageIndex, totalPageCount > 0 ? totalPageCount : 1));
            int offset = (pageIndex - 1) * pageSize;

            List<Product> productList = productService.getProductList(
                    productName, null, null, categoryLevel3Id, offset, pageSize);

            logger.debug("商品列表查询 - 名称: {}, 三级分类ID: {}, 页码: {}, 数量: {}",
                    productName, categoryLevel3Id, pageIndex, productList.size());

            // 获取所有三级分类用于搜索下拉框
            List<ProductCategory> categoryList = productCategoryService.getCategoryByType(3);

            model.addAttribute("productList", productList);
            model.addAttribute("totalPageCount", totalPageCount);
            model.addAttribute("pageIndex", pageIndex);
            model.addAttribute("productName", productName);
            model.addAttribute("categoryLevel3Id", categoryLevel3Id);
            model.addAttribute("categoryList", categoryList);

            return "productlist";
        } catch (Exception e) {
            logger.error("查询商品列表异常", e);
            model.addAttribute("errorMsg", "系统异常，请稍后再试");
            return "error/500";
        }
    }

    @GetMapping(value = {"/add", "/add.html"})
    public String addProductPage(Model model, HttpSession session) {
        try {
            List<ProductCategory> categoryLevel3List = productCategoryService.getCategoryByType(3);
            model.addAttribute("categoryLevel3List", categoryLevel3List);
            logger.debug("加载三级分类数据，数量: {}", categoryLevel3List.size());
            return "productadd";
        } catch (Exception e) {
            logger.error("加载分类数据异常", e);
            model.addAttribute("errorMsg", "加载分类数据失败，请稍后再试");
            return "error/500";
        }
    }

    @PostMapping(value = {"/add", "/add.html"})
    public String addProduct(Product product, HttpSession session, Model model) {
        try {
            // 设置公共参数
            product.setCreatedBy(1L);
            product.setCreationDate(new Timestamp(System.currentTimeMillis()));
            product.setIsDelete(0);

            // 修复：确保价格和库存是BigDecimal类型
            if (product.getPrice() == null) {
                product.setPrice(BigDecimal.ZERO);
            }
            if (product.getStock() == null) {
                product.setStock(BigDecimal.ZERO);
            }

            boolean result = productService.add(product);
            if (result) {
                logger.info("商品添加成功，商品ID: {}", product.getId());
                return PRODUCT_LIST_REDIRECT;
            }
            model.addAttribute("message", "添加失败，请检查数据是否完整");
            logger.warn("商品添加失败，商品名称: {}", product.getName());

            // 重新加载分类数据
            List<ProductCategory> categoryLevel3List = productCategoryService.getCategoryByType(3);
            model.addAttribute("categoryLevel3List", categoryLevel3List);

            return "productadd";
        } catch (Exception e) {
            model.addAttribute("message", "添加异常: " + e.getMessage());
            logger.error("商品添加异常，商品名称: {}", product.getName(), e);

            // 重新加载分类数据
            List<ProductCategory> categoryLevel3List = productCategoryService.getCategoryByType(3);
            model.addAttribute("categoryLevel3List", categoryLevel3List);

            return "productadd";
        }
    }

    @GetMapping("/modify/{id}")
    public String modifyProductPage(@PathVariable Integer id, Model model) {
        try {
            Product product = productService.getProductById(id);
            List<ProductCategory> categoryLevel3List = productCategoryService.getCategoryByType(3);

            model.addAttribute("product", product);
            model.addAttribute("categoryLevel3List", categoryLevel3List);

            logger.debug("加载商品修改数据，商品ID: {}", id);
            return "productmodify";
        } catch (Exception e) {
            logger.error("加载商品修改数据异常，商品ID: {}", id, e);
            model.addAttribute("errorMsg", "加载商品数据失败，请稍后再试");
            return "error/500";
        }
    }

    @PostMapping(value = {"/modify", "/modify.html"})
    public String modifyProduct(Product product, Model model) {
        try {
            // 设置公共参数
            product.setModifyBy(1L);
            product.setModifyDate(new Timestamp(System.currentTimeMillis()));

            // 修复：确保价格和库存是BigDecimal类型
            if (product.getPrice() == null) {
                product.setPrice(BigDecimal.ZERO);
            }
            if (product.getStock() == null) {
                product.setStock(BigDecimal.ZERO);
            }

            boolean result = productService.modify(product);
            if (result) {
                logger.info("商品修改成功，商品ID: {}", product.getId());
                return PRODUCT_LIST_REDIRECT;
            }
            model.addAttribute("message", "修改失败，请检查数据是否完整");
            logger.warn("商品修改失败，商品ID: {}", product.getId());

            // 重新加载数据
            Product updatedProduct = productService.getProductById(product.getId());
            List<ProductCategory> categoryLevel3List = productCategoryService.getCategoryByType(3);
            model.addAttribute("product", updatedProduct);
            model.addAttribute("categoryLevel3List", categoryLevel3List);

            return "productmodify";
        } catch (Exception e) {
            model.addAttribute("message", "修改异常: " + e.getMessage());
            logger.error("商品修改异常，商品ID: {}", product.getId(), e);

            // 重新加载数据
            try {
                Product updatedProduct = productService.getProductById(product.getId());
                List<ProductCategory> categoryLevel3List = productCategoryService.getCategoryByType(3);
                model.addAttribute("product", updatedProduct);
                model.addAttribute("categoryLevel3List", categoryLevel3List);
            } catch (Exception ex) {
                logger.error("重新加载商品数据失败", ex);
            }

            return "productmodify";
        }
    }

    @GetMapping("/view/{id}")
    public String viewProduct(@PathVariable Integer id, Model model) {
        try {
            Product product = productService.getProductById(id);
            model.addAttribute("product", product);
            return "productview";
        } catch (Exception e) {
            logger.error("加载商品详情异常，商品ID: {}", id, e);
            model.addAttribute("errorMsg", "加载商品详情失败");
            return "error/500";
        }
    }

    @GetMapping("/delete/{id}")
    public String deleteProduct(@PathVariable Integer id, Model model) {
        try {
            boolean success = productService.deleteProductById(id);
            if (success) {
                logger.info("商品删除成功，商品ID: {}", id);
            } else {
                logger.warn("商品删除失败，商品ID: {}", id);
                model.addAttribute("errorMsg", "删除商品失败");
            }
            return PRODUCT_LIST_REDIRECT;
        } catch (Exception e) {
            logger.error("商品删除异常，商品ID: {}", id, e);
            model.addAttribute("errorMsg", "删除商品时发生错误");
            return "error/500";
        }
    }
}